﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;

namespace Muccu.Web
{
    /// <summary>
    /// Handler for Html forms framework
    /// </summary>
    public class HtmlFormHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }

        private static Regex scriptre = new Regex(@"\<head(.*)head>", RegexOptions.IgnoreCase | RegexOptions.Singleline);

        public void ProcessRequest(HttpContext context)
        {
            var relativePath = VirtualPathUtility.ToAppRelative(context.Request.FilePath);
            var path = relativePath.Replace("~/", "~/__forms/").Replace(".frm", ".htm");
            path = context.Server.MapPath(path);
            // TODO: Caching
            if (File.Exists(path))
            {
                var sr = File.OpenText(path);

                var html = sr.ReadToEnd();
                int pos = 0;
                Match m;
                StringBuilder sb = new StringBuilder();

                while (pos < html.Length)
                {
                    if ((m = scriptre.Match(html, pos)).Success)
                    {
                        sb.Append(html.Substring(pos, m.Index - pos));
                        pos = m.Index + m.Length;
                    }
                    else
                    {
                        sb.Append(html.Substring(pos, html.Length - pos));
                        pos = html.Length;
                    }
                }
                sr.Close();
                context.Response.Write(sb.ToString());
            }
            else
            {
                context.Response.StatusCode = 403;
            }
        }
    }
}
